package com.chunfeng.lerunapplication.fragement;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import com.chunfeng.lerunapplication.R;
import com.chunfeng.lerunapplication.api.UserApi;
import com.chunfeng.lerunapplication.dialog.UpdateUserDialog;
import com.chunfeng.lerunapplication.entity.JsonRequest;
import com.chunfeng.lerunapplication.entity.User;
import com.chunfeng.lerunapplication.utils.CacheUtils;
import com.chunfeng.lerunapplication.utils.JsonSerializeUtils;
import com.chunfeng.lerunapplication.utils.PathUtils;
import com.chunfeng.lerunapplication.utils.TokenUtils;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.util.Objects;

/**
 * 我的
 */
public class MeFragment extends Fragment implements View.OnClickListener {
    /**
     * 标识申请的是什么权限
     */
    public static final int STORAGE_PERMISSION = 1;
    /**
     * 文件返回data
     */
    private static final int CHOOSE_PHOTO = 1;
    /**
     * 用户名
     */
    private EditText name;
    /**
     * 手机号
     */
    private EditText phone;
    /**
     * 地址
     */
    private EditText address;
    /**
     * 创建时间
     */
    private EditText createTime;
    /**
     * 头像组件
     */
    private ImageView avatar;
    /**
     * 上传文件
     */
    private Button uploadAvatarButton;
    /**
     * 修改用户
     */
    private Button updateUserButton;
    /**
     * 用户接口
     */
    private UserApi userApi;
    /**
     * 用户信息
     */
    private User user;
    /**
     * 图片字节
     */
    private byte[] imageByte;
    /**
     * 当前的主activity
     */
    private Activity activity;


    /**
     * 带参构造
     *
     * @param activity 父activity
     */
    public MeFragment(Activity activity) {
        this.activity = activity;
    }

    /**
     * 关闭页面
     */
    private void closeActivity() {
        activity.finish();
    }

    /**
     * 初始化
     *
     * @param savedInstanceState 状态
     */
    @Override
    public void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        userApi = new UserApi(getContext());
        initData();
    }


    /**
     * 初始化数据
     */
    private void initData() {
        String token = new CacheUtils(getContext()).getValue("token");
        if (token.isEmpty()) {
            return;
        }
        Integer userId = TokenUtils.checkToken(token, Integer.class);
        if (userId == null) {
            return;
        }
        JsonRequest<?> jsonRequest = userApi.lookCurrentUser(userId);
        if (jsonRequest == null) {
            return;
        }
        if (!jsonRequest.getSuccess()) {
            Toast.makeText(getContext(), "当前登录信息已失效,请重新登录!", Toast.LENGTH_SHORT).show();
            return;
        }
        Object data = jsonRequest.getData();
        //二次转换
        user = JsonSerializeUtils.reSerialize(data, User.class);
        imageByte = userApi.downloadAvatar(user.getId());
    }

    /**
     * 渲染数据
     */
    private void showData() {
        if (Objects.nonNull(user)) {
            avatar.setImageBitmap(BitmapFactory.decodeByteArray(imageByte, 0, imageByte.length));
            name.setText(user.getName());
            phone.setText(user.getPhone());
            address.setText(user.getAddressInfo());
            createTime.setText(user.getCreateTime());
        }
    }

    /**
     * 渲染视图并初始化组件
     *
     * @param inflater           布局反射器
     * @param container          父容器
     * @param savedInstanceState 状态
     * @return 布局对象
     */
    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_me, container, false);
        avatar = view.findViewById(R.id.Avatar);
        name = view.findViewById(R.id.EditText_Name);
        phone = view.findViewById(R.id.EditText_Phone);
        address = view.findViewById(R.id.EditText_Address);
        createTime = view.findViewById(R.id.EditText_CreateTime);
        uploadAvatarButton = view.findViewById(R.id.Button_UploadAvatar);
        updateUserButton = view.findViewById(R.id.Button_UpdateUser);
        uploadAvatarButton.setOnClickListener(this);
        updateUserButton.setOnClickListener(this);
        showData();
        return view;
    }

    /**
     * 点击事件
     *
     * @param v 被点击的组件
     */
    @Override
    public void onClick(View v) {
        int id = v.getId();
        User user1 = new User(user.getId(), user.getName(), user.getPhone());
        //修改用户
        if (id == R.id.Button_UpdateUser) {
            UpdateUserDialog userDialog = new UpdateUserDialog(getContext())
                    .setTitle("修改用户")
                    .setUsername(user1.getName())
                    .setPhone(user1.getPhone())
                    .setCancelButtonOnClickListener(Dialog::dismiss)
                    .setSubmitButtonOnClickListener(dialog -> {
                        User currentUser = dialog.getCurrentUser(user1.getId());
                        if (currentUser == null) {
                            return;
                        }
                        if (updateUser(currentUser)) {
                            closeActivity();
                        }
                    });
            userDialog.show();
        }
        //上传头像
        else if (id == R.id.Button_UploadAvatar) {
            if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, STORAGE_PERMISSION);
            } else {
                getImageList();
            }
        }
    }

    /**
     * 请求图像资源
     */
    private void getImageList() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO); // 打开本地存储
    }

    /**
     * 权限请求回调
     *
     * @param requestCode  请求代码
     * @param permissions  权限代码
     * @param grantResults 结果
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull @NotNull String[] permissions, @NonNull @NotNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == STORAGE_PERMISSION) {//检查是否有读取存储卡的权限，如果有则选择图片，如果没有则提示
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getImageList();
            } else {
                Toast.makeText(getContext(), "请先允许权限!", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 得到图片结果
     *
     * @param requestCode 请求代码
     * @param resultCode  结果
     * @param data        数据
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CHOOSE_PHOTO) {
            //获取真实图片路径
            String realPath = PathUtils.getRealPath(getContext(), data);
            File file = new File(realPath);
            if (file.length() > 1048576) {
                Toast.makeText(activity, "图片大小不得超过1MB!", Toast.LENGTH_SHORT).show();
                return;
            }
            JsonRequest<Integer> jsonRequest = userApi.uploadAvatar(user.getId(), file);
            if (!jsonRequest.getSuccess()) {
                Toast.makeText(activity, jsonRequest.getMessage(), Toast.LENGTH_SHORT).show();
                return;
            }
            Toast.makeText(activity, "上传头像成功!", Toast.LENGTH_SHORT).show();
            imageByte = userApi.downloadAvatar(user.getId());
            showData();
        }
    }

    /**
     * 修改用户
     *
     * @param user 用户信息
     */
    private Boolean updateUser(User user) {
        JsonRequest<Integer> jsonRequest = userApi.updateCurrentUser(user);
        if (jsonRequest == null) {
            return false;
        }
        if (!jsonRequest.getSuccess()) {
            Toast.makeText(getContext(), "修改失败!", Toast.LENGTH_SHORT).show();
            return false;
        }
        Toast.makeText(getContext(), "修改成功!请重新登录!", Toast.LENGTH_SHORT).show();
        return true;
    }
}